package com.tsunami.user.interceptor;

import com.tsunami.context.BaseContextConstants;
import com.tsunami.context.BaseContextHandler;
import com.tsunami.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

/**
 * @Classname ContextHandlerInterceptor
 * @Description TODO
 * @Date 2021-11-02 17:03
 * @Created by lx
 */
@Slf4j
public class ContextHandlerInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            if (!(handler instanceof HandlerMethod)) {
                log.info("not exec!!! url={}", request.getRequestURL());
                return super.preHandle(request, response, handler);
            }
            String userId = getHeader(request, BaseContextConstants.JWT_KEY_USER_ID);
            String account = getHeader(request, BaseContextConstants.JWT_KEY_ACCOUNT);
//            String name = getHeader(request, BaseContextConstants.JWT_KEY_NAME);
//            String orgId = getHeader(request, BaseContextConstants.JWT_KEY_ORG_ID);
            String clientId = getHeader(request, BaseContextConstants.JWT_KEY_CLIENT_ID);
            BaseContextHandler.setUserId(userId);
            BaseContextHandler.setAccount(account);
            BaseContextHandler.setClientId(clientId);
        } catch (Exception e) {
            log.warn("解析token信息时，发生异常. ", e);
        }
        return super.preHandle(request, response, handler);
    }

    private String getHeader(HttpServletRequest request, String name) throws UnsupportedEncodingException {
        String value = request.getHeader(name);
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        return URLDecoder.decode(value, "utf-8");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        BaseContextHandler.remove();
        super.afterCompletion(request, response, handler, ex);
    }
}
